package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.security.util.Des3Utils;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.WuYiWeiQianBaoParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceCallBackService;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class WuYiWeiQianBaoReceiveService extends ISourceReceiveService implements ISourceCallBackService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();
        String apiKey = sourceBaseInfo.getApiKey();
        String channelCode = sourceBaseInfo.getChannelCode();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        String companyId = jsonObjectParamContent.getString("channelCode");
        if (!channelCode.equals(companyId)){
            sourceApiResult.setReturnObject(this.getError("渠道编号不符合"));
            return sourceApiResult;
        }
        String data = jsonObjectParamContent.getString("data");
        String paramContentData = Des3Utils.java_openssl_decrypt(data,apiKey,apiSecret);
        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("phoneMd5")) ||
                StrUtil.isEmpty(jsonObject.getString("name")) ||
                jsonObject.getInteger("sex") == null ||
                jsonObject.getInteger("age") == null ||
                StrUtil.isEmpty(jsonObject.getString("city")) ||
                jsonObject.getInteger("loanMoney") == null ||
                jsonObject.getInteger("social") == null ||
                jsonObject.getInteger("fund") == null ||
                jsonObject.getInteger("car") == null ||
                jsonObject.getInteger("house") == null ||
                jsonObject.getInteger("credit") == null ||
                jsonObject.getInteger("insurance") == null ||
                jsonObject.getInteger("study") == null ||
                jsonObject.getInteger("job") == null ||
                jsonObject.getInteger("overdue") == null ||
                jsonObject.getInteger("flowers") == null ||
                jsonObject.getInteger("whiteNote") == null ||
                jsonObject.getInteger("seed") == null){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }

        WuYiWeiQianBaoParam wuYiWeiQianBaoParam = JSON.parseObject(paramContentData, WuYiWeiQianBaoParam.class);
        UserDataParam userDataParam = this.getUserDataParam(paramContentData);


        // 获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddresInfoByCity(userDataParam.getCity());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        userDataParam.setMobileMd5(wuYiWeiQianBaoParam.getPhoneMd5());

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());



        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();
        String channelCode = sourceBaseInfo.getChannelCode();
        String apiKey = sourceBaseInfo.getApiKey();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        String companyId = jsonObjectParamContent.getString("channelCode");
        if (!channelCode.equals(companyId)){
            sourceApiResult.setReturnObject(this.getError("渠道编号不符合"));
            return sourceApiResult;
        }
        String data = jsonObjectParamContent.getString("data");
        String paramContentData = Des3Utils.java_openssl_decrypt(data,apiKey,apiSecret);

        WuYiWeiQianBaoParam wuYiWeiQianBaoParam = JSON.parseObject(paramContentData, WuYiWeiQianBaoParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        userDataParam.setMobile(wuYiWeiQianBaoParam.getPhone());
        userDataParam.setRealName(wuYiWeiQianBaoParam.getName());

        String requestId = wuYiWeiQianBaoParam.getApplyNo();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), requestId);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "SUCCESS！");
        JSONObject dataObject = new JSONObject();
        dataObject.put("status", "1");
        dataObject.put("applyNo", pushResultInfo.getOutOrderNo());

        returnObject.put("data", dataObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject.put("code", 200);
                returnObject.put("msg", "操作成功！");
                JSONObject dataObject = new JSONObject();
                dataObject.put("status","1");
                dataObject.put("applyNo", pushResultInfo.getOutOrderNo());
                JSONArray jsonArray = new JSONArray();

                if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())) {
                    dataObject.put("instName", thirdBaseInfo.getCompanyName());
                    dataObject.put("companyAddress", thirdBaseInfo.getCompanyName());
                    dataObject.put("companyName", thirdBaseInfo.getInfoName());
                    //协议地址
                    for (MerchantThirdProtocolInfo protocolInfo : thirdProtocolInfoList) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("name", protocolInfo.getProtocolName());
                        jsonObject.put("url", protocolInfo.getProtocolUrl());
                        jsonArray.add(jsonObject);
                    }
                }else {
                    JSONObject jsonObject = new JSONObject();
                    dataObject.put("instName", merchantBaseInfo.getCompanyName());
                    dataObject.put("companyAddress", merchantBaseInfo.getCompanyName());
                    dataObject.put("companyName", merchantBaseInfo.getInfoName());
                    ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
                    ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
                    String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
                    jsonObject.put("name", "授权协议");
                    jsonObject.put("url", protocolUrl);
                    jsonArray.add(jsonObject);
                }

                dataObject.put("agreementUrl",jsonArray);
                returnObject.put("data", dataObject);
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 500);
        returnObject.put("msg", message);
        returnObject.put("data", new JSONObject());
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "推送成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        WuYiWeiQianBaoParam wuYiWeiQianBaoParam = JSON.parseObject(paramContent, WuYiWeiQianBaoParam.class);

        UserDataParam userDataParam = new UserDataParam();

        Integer randomInt = RandomUtil.randomInt(Integer.MAX_VALUE);
        userDataParam.setOutOrderNo(String.valueOf(randomInt));

//        userDataParam.setMobileMd5(wuYiWeiQianBaoParam.getPhoneMd5());
//        userDataParam.setMobile(wuYiWeiQianBaoParam.getPhone());
        userDataParam.setRealName(wuYiWeiQianBaoParam.getName());

        if (wuYiWeiQianBaoParam.getSex() == 1){
            userDataParam.setSex("1");
        }else {
            userDataParam.setSex("2");
        }

        userDataParam.setAge(wuYiWeiQianBaoParam.getAge());

        userDataParam.setCity(wuYiWeiQianBaoParam.getCity());

        Integer credit = wuYiWeiQianBaoParam.getCredit();
        if (credit == 0){
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk002.getValue());
        }


        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());

        Integer study = wuYiWeiQianBaoParam.getStudy();
        if (study == 0){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        }else {
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl004.getValue());
        }


        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());

        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());

        if (wuYiWeiQianBaoParam.getWhiteNote() == 0){
            userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        }else {
            userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt002.getValue());
        }

        if (wuYiWeiQianBaoParam.getFlowers() == 0){
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        }else {
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb002.getValue());
        }

        userDataParam.setUserIp("127.0.0.1");

        Integer loanAmount = wuYiWeiQianBaoParam.getLoanMoney();
        if (loanAmount == 0 || loanAmount == 1) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        } else if (loanAmount == 2) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        } else if (loanAmount == 3) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        } else if (loanAmount == 4) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        } else {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }


        Integer houseProperty = wuYiWeiQianBaoParam.getHouse();
        if (houseProperty == 0){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else if (houseProperty == 2){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
        }else {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu004.getValue());
        }

        Integer commercialInsurance = wuYiWeiQianBaoParam.getInsurance();
        if (commercialInsurance == 0){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else {
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx003.getValue());
        }

        Integer creditCardLimit = wuYiWeiQianBaoParam.getOverdue();
        if (creditCardLimit == 0){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }else {
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq002.getValue());
        }

        Integer hasFund = wuYiWeiQianBaoParam.getFund();
        if (hasFund == 0){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else if (hasFund == 1){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
        }else {
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
        }

        Integer zhimaCredit = wuYiWeiQianBaoParam.getSeed();
        if (zhimaCredit == 4){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }else if (zhimaCredit == 3){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else if (zhimaCredit == 2){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else if (zhimaCredit == 1){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }else {
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm001.getValue());
        }

        Integer hasSocial = wuYiWeiQianBaoParam.getSocial();
        if (hasSocial == 0){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else if (hasSocial == 1){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb002.getValue());
        }else {
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
        }

        Integer carProperty = wuYiWeiQianBaoParam.getCar();
        if (carProperty == 0){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else if (carProperty == 2){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
        }else {
            userDataParam.setCar(BaseTypeInfoEnum.Car.car003.getValue());
        }

        Integer professional = wuYiWeiQianBaoParam.getJob();
        if (professional == 0 || professional == 1){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else if (professional == 3){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }else{
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
        }

        userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());


        return userDataParam;
    }

    @Override
    public SourceApiResult getCallBack1Data(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "申请成功");

        sourceApiResult.setCallBack1Data(jsonObject);

        return sourceApiResult;
    }
}
